﻿#include "TreeWidgetEventFilter.h"
#include <QTreeWidgetItem>
#include <qevent.h>
#include <qdebug.h>
#include <QHeaderView>
#include <QMainWindow>

bool TreeWidgetEventFilter::eventFilter(QObject* watched, QEvent* event) {
	QTreeWidget* widget = qobject_cast<QTreeWidget*>(watched);
	static QPoint oldPoint;
	static QPoint newPoint;
	QEvent::Type eventType = event->type( );
	if( eventType == QEvent::MouseButtonPress ) {
		newPoint = QCursor::pos( );
		// qDebug( ) << newPoint;
	}
	if( eventType == QEvent::MouseButtonRelease ) {
		oldPoint = newPoint;
	}
	if( eventType == QEvent::MouseMove && oldPoint != newPoint ) {
		// qDebug( ) << "产生了移动";
		if( horScrollBar->isEnabled( ) ) {
			if( oldPoint.x( ) > newPoint.x( ) ) {
				int horScrollBarValue = horScrollBar->value( );
				int newValue = horScrollBarValue + 2;
				int maximum = horScrollBar->maximum( );
				if( newValue >= maximum ) {
					horScrollBar->setValue(newValue);
				} else {
					horScrollBar->setValue(maximum);
				}
			}
			if( oldPoint.x( ) < newPoint.x( ) ) {
				int horScrollBarValue = horScrollBar->value( );
				int newValue = horScrollBarValue - 2;
				int minimum = horScrollBar->minimum( );
				if( newValue >= minimum ) {
					horScrollBar->setValue(newValue);
				} else {
					horScrollBar->setValue(minimum);
				}
			}
		}
		oldPoint = newPoint;
	}
	return QObject::eventFilter(watched, event);
}

TreeWidgetEventFilter::TreeWidgetEventFilter(QTreeWidget* parent): QObject(parent) {
	horScrollBar = parent->header( )->horizontalScrollBar( );
	verScrollBar = parent->header( )->verticalScrollBar( );
	parent->installEventFilter(this);
}

TreeWidgetEventFilter::~TreeWidgetEventFilter( ) {}
